# coding=utf-8
import redis
import pymongo
import bson
import time
import argparse
from urllib import quote_plus

config = {
    "local": {"redis": {"host":'localhost', "port":6379},
                "mongo": {"hosts":['localhost:27017']}},
    "qa": {"redis":{"host":'10.22.114.103', "port":6379},
            "mongo":{"hosts":['10.22.114.91:27017', '10.22.114.91:27017'], "username":"xdmp", "password":"20E6QK8V", 
                    "sourceDB": "admin", "replicaSetName":"xd-online"}},
    "mini": {"redis":{"host":'10.22.111.159', "port":6379},
              "mongo":{"hosts":['10.22.111.149:27017', '10.22.111.150:27017'], "username":"xdmp", "password":"20E6QK8V", 
                    "sourceDB": "admin", "replicaSetName":"xd-online"}}
}
redis_config = {}
mongo_config = {}

def get_datasync_shopid(switch):
    r = redis.Redis(host = redis_config["host"],  db = 0)
    keys = r.keys("mini_data_switch:*")
    print("keys:", keys)
    shops = []
    for key in keys:
        switchStatus = r.get(key)
        if switchStatus != switch: 
            continue
        splits = key.split(":")
        if len(splits) < 2:
            print("unvalid key:%s".format(key))
            continue
        shops.append(splits[1])
    print("switch filter:{0} total_key:{1} valid:{2}".format(switch, len(keys), len(shops)))
    return shops

def get_shop_by_shopid(shop_ids, platform):
    options = {
        'host': mongo_config["hosts"],
    }
    if mongo_config.has_key("replicaSetName"):
        options['authSource'] = mongo_config["sourceDB"]
        options['replicaSet'] = mongo_config["replicaSetName"]
        options['username'] = quote_plus(mongo_config["username"])
        options['password'] = quote_plus(mongo_config["password"])
    mgocli = pymongo.MongoClient(**options)
    collect = mgocli["xdmp"]["shop"]

    shops = []
    for i, shop_id in enumerate(shop_ids):
        print("handle index:{0} shop:{1}".format(i, shop_id))
        shop_info = collect.find_one({"_id":bson.ObjectId(shop_id)})
        if shop_info is None:
            print("shop_id:{0} not found".format(shop_id))
            continue
        if platform != shop_info["platform"]:
            continue
        shops.append(shop_info)
        time.sleep(0.02)
    print("total shop:{0} valid_shop:{1}".format(len(shop_ids), len(shops)))
    return shops

def write_shop_to_file(shops, filename):
    with open(filename, "w") as fp:
        fp.writelines(['\t'.join((str(shop["_id"]), shop["plat_user_id"], shop["platform"])).encode('utf-8') + '\n' for shop in shops])

if __name__ == "__main__":
    parser = argparse.ArgumentParser() 
    parser.add_argument(dest="env", help="local or qa or mini", choices=("local", "qa", "mini"), type=str)
    args = parser.parse_args()
    env_config = config[args.env]
    redis_config = env_config["redis"]
    mongo_config = env_config["mongo"]

    shop_ids = get_datasync_shopid("on")
    shops = get_shop_by_shopid(shop_ids, "tb")
    write_shop_to_file(shops, "datasync_shop.{0}.txt".format(args.env))
